package cn.chencaiju.blog.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.chencaiju.blog.domain.AjaxResponse;
import cn.chencaiju.blog.domain.Post;
import cn.chencaiju.blog.mapper.PostMapper;


@Service
//相当于在当前类的每个方法上加上了切面，
//方法执行之前，会开始事务，执行完后，会提交事务，关闭session
@Transactional 
public class PostService {
	@Autowired
	private PostMapper mapper=null;
	
	public AjaxResponse<Post> page(){
		List<Post> list = mapper.selectAll();
		int count = mapper.count();
		AjaxResponse<Post> ajax=new AjaxResponse<>();
		ajax.setData(list);
		ajax.setCount(count);
		ajax.setCode(0);
		ajax.setMsg("successed");

		return ajax;
	}
	public AjaxResponse<Post> page(String pages, String limit) {
		int size=Integer.valueOf(limit);
		int start=(Integer.valueOf(pages)- 1) * size;
		return page(start,size);
	}
	private AjaxResponse<Post> page(int pages, int limit) {
		List<Post> list = mapper.page(pages,limit);
		int count=mapper.count();
		AjaxResponse<Post> response=new AjaxResponse<>();
		response.setCode(0);
		response.setCount(count);
		response.setData(list);
		response.setMsg("successed");
		return response;
	}
	public int deleteBatch(String[] ids) {
		return mapper.deleteBatch(ids);		
	}
	public int insert(String title, String cid, String content) {
		Post post=new Post();
		post.setTitle(title);
		if(cid!=null&&cid!="") {
			post.setCid(Integer.valueOf(cid));
		}
		return mapper.insert(post);
		
	}
	public List<Post> search(String title, String cid, String created) {
		Post post=new Post();
		post.setTitle(title);
		if(cid!=null&&cid!="") {
			post.setCid(Integer.valueOf(cid));
		}
		return mapper.search(post);
		
	}
	public int count() {
		return mapper.count();
		
	}
}
